import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: () => import('@/views/login') },
    {
      path: '/',
      component: () => import('@/views/layout'),
      redirect: '/home',
      children: [
        { path: 'home', component: () => import('@/views/layout/home') },
        { path: 'category', component: () => import('@/views/layout/category') },
        { path: 'cart', component: () => import('@/views/layout/cart') },
        { path: 'user', component: () => import('@/views/layout/user') }
      ]
    },
    { path: '/search', component: () => import('@/views/search') },
    { path: '/searchList', component: () => import('@/views/search/list') },
    { path: '/proDetail/:id', component: () => import('@/views/proDetail') },
    { path: '/pay', component: () => import('@/views/pay') },
    { path: '/myOrder', component: () => import('@/views/myOrder') }
  ]
})

const authUrl = ['/pay', '/myOrder']
// 路由前置守卫
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  if (!authUrl.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  // console.log('token:', token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
